import 'package:cloud_medicine/components/tag.dart';
import 'package:cloud_medicine/components/user_avatar.dart';
import 'package:cloud_medicine/components/util.dart';
import 'package:cloud_medicine/http/doctor_api.dart';
import 'package:cloud_medicine/http/user_api.dart';
import 'package:cloud_medicine/pages/user_verify.dart';
import 'package:flutter/material.dart';
import 'package:cloud_medicine/model/base_user_info.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MyBasicInfo extends StatefulWidget {
  final BaseUserInfo user;

  MyBasicInfo({Key key, @required this.user}) : super(key: key);

  @override
  _MyBasicInfoState createState() => _MyBasicInfoState();
}

class _MyBasicInfoState extends State<MyBasicInfo> {
  static const double imageStyle = 80; // 未登录和登录时的图片样式（宽、高）
  static const containerBorderRadius =
      Radius.circular(20); // 用户基本信息显示部分的左上角和右下角的圆角
  int radioStatusID = 0;

  @override
  void initState() {
    super.initState();
    getUserInfo();
    if (widget.user != null) {
      setState(() {
        radioStatusID = widget.user.statusID;
      });
      print('--------------');
      print(widget.user.statusID);
    }
  }

  void getUserInfo() async {
    // 持久化存储
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String token = prefs.getString('Authorization'); // 获取本地存储的token
    if (token != null) {
      // TODO: 获取后端的数据
    }
  }

  _infoItem(IconData icon, Color color, String text) {
    return Row(
      children: <Widget>[
        Icon(icon, color: color),
        SizedBox(width: 5),
        Text(text),
      ],
    );
  }

  entryUserVerify() {
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (context) => UserVerifyPage()));
  }

  _showDoctorSelect() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        height: 180,
        child: Column(
          children: <Widget>[_item('空闲', 7), _item('忙碌', 8), _item('离线', 9)],
        ),
      ),
    );
  }

  // 在底部生成每一项部件
  _item(String title, int status) {
    Map<int, IconData> contrastIcons = {
      7: Icons.report,
      8: Icons.do_not_disturb_on,
      9: Icons.alarm_off,
    };
    Map<int, Color> contrastColors = {
      7: Colors.green,
      8: Colors.yellow,
      9: Colors.red,
    };
    final Widget icon =
        Icon(contrastIcons[status], color: contrastColors[status]);

    // 修改用户状态
    modifyStatus() async {
      dynamic res = await alterDoctorStatus_api({
        'statusID': status,
      });
      res['code'] == 0 ? successToast('修改状态成功') : errorToast(res['message']);
      await getBasicUserInfo_api();
      setState(() {
        radioStatusID = status;
      });
      Navigator.pop(context);
    }

    return GestureDetector(
      child: ListTile(
        leading: icon,
        title: Text(title),
        onTap: modifyStatus,
        trailing: Radio(
          groupValue: radioStatusID,
          activeColor: Colors.blue,
          value: status,
          onChanged: (int val) {
            modifyStatus();
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget infoShow = Row(
      children: <Widget>[
        Container(
          width: imageStyle,
          height: imageStyle,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(imageStyle / 2),
            child: Image.asset('images/defaultAvatar.jpg'),
          ),
        ),
        SizedBox(
          width: 20,
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              '点击登录',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 10),
            Text(
              '让病痛远离世界',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        )
      ],
    );

    // 条件渲染
    // 如果有用户数据则渲染用户数据
    if (widget.user != null) {
      infoShow = Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                children: <Widget>[
                  UserAvatar(avatar: user.avatar),
                  SizedBox(width: 20),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        user.realname,
                        style: TextStyle(
                          fontSize: 30,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      SizedBox(height: 10),
                      Row(
                        children: <Widget>[
                          Tag(
                            text: user.identify.value,
                            bgColor: Colors.green,
                          ),
                          SizedBox(width: 10),
                          widget.user.identify.id == 4 && widget.user.statusID != 0
                              ? GestureDetector(
                                  child: Tag(
                                    text: getDoctorStatusInfo(
                                        radioStatusID, 'text'),
                                    bgColor: getDoctorStatusInfo(
                                        radioStatusID, 'bgColor'),
                                  ),
                                  onTap: _showDoctorSelect,
                                )
                              : Container(),
                        ],
                      ),
                    ],
                  )
                ],
              ),
              widget.user.identify.id == 0
                  ? RaisedButton(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(
                          Radius.circular(20),
                        ),
                      ),
                      color: Colors.greenAccent,
                      textColor: Colors.white,
                      child: Text('点击验证'),
                      onPressed: entryUserVerify,
                    )
                  : Icon(Icons.arrow_forward_ios, size: 16)
            ],
          ),
          SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              _infoItem(
                  Icons.monetization_on, Colors.yellow, user.money),
              _infoItem(Icons.assignment, Colors.lightBlueAccent, user.postNum),
              _infoItem(Icons.favorite, Colors.redAccent, user.likeNum),
              _infoItem(Icons.star, Colors.yellow, user.collectNum),
              Container(
                width: 70,
                child: RaisedButton(
                  onPressed: () {},
                  color: Colors.lightBlueAccent,
                  textColor: Colors.white,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(
                      Radius.circular(20),
                    ),
                  ),
                  child: Text('充值'),
                ),
              )
            ],
          )
        ],
      );
    }
    return GestureDetector(
      onTap: () {
        if (user == null) {
          Navigator.pushNamed(context, '/loginSelect');
        } else {
          Navigator.pushNamed(context, '/user');
        }
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              topLeft: containerBorderRadius, topRight: containerBorderRadius),
          color: Colors.white,
        ),
        margin: EdgeInsets.only(left: 20, right: 20, top: 20),
        padding: EdgeInsets.all(10),
        child: infoShow,
      ),
    );
  }
}
